package cg.studio.practise.laddersnake;

import java.util.HashMap;
import java.util.Map;

public class DeliverGame
{
  private final int size;
  private int curPosition = 1;
  private boolean showRoute = true; 
  
  //use map ( source ==> destination ) to represents the ladders and snakes
  private Map< Integer, Integer > delivers = new HashMap< Integer, Integer >();
  
  public DeliverGame( int edgeSize )
  {
    size = edgeSize * edgeSize;
  }
  
  public void addDeliver( int src, int dest )
  {
    if( src < 1 || src > size || dest < 1 || dest > size )
      throw new IllegalArgumentException( "Invalid src or dest." );
    delivers.put( src, dest );
  }
  
  /**
   * start with 1, and reach size means game finished.
   */
  public void play()
  {
    while( true )
    {
      int dice = getDice();
      if( showRoute )
      {
        System.out.print( "Dice: " + dice + ". " );
        System.out.println( "Position changed: " + curPosition + " --> " + (curPosition+dice) );
      }
      curPosition += dice;
      if( curPosition >= size )
        break;
      while( true )
      {
        boolean changed = positionChanged();
        if( curPosition == size )
          break;
        if( !changed )
          break;
      }

      if( curPosition == size )
        break;
    }
    System.out.println( "Game end." );
  }
  
  /*
   * trigger this function is position changed.
   * return true if this function change the poisition
   */
  protected boolean positionChanged()
  {
    Integer dest = delivers.get( curPosition );
    if( dest != null )
    {
      if( showRoute )
      {
        System.out.print( "deliver: " );
        System.out.println( "Position changed: " + curPosition + " --> " + dest );
      }

      curPosition = dest;
      return true;
    }
    return false;
  }
  
  // return random [1-6]
  protected int getDice()
  {
    return (int)( Math.random()*6 ) + 1;
  }
  
  public int getSize()
  {
    return size;
  }
}
